package com.general.framework.qinyi.guide.postProcessor;

import lombok.extern.slf4j.Slf4j;
import org.qinyi.guide.CouponHandlerProcessor;
import org.qinyi.guide.CouponTypeEnum;
import org.qinyi.guide.couponHandler.ICouponHandlerService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * coupon 处理器工厂类
 */
@Slf4j
@Component
public class CouponHandlerFactory implements BeanPostProcessor {
    private static final Map<CouponTypeEnum, ICouponHandlerService> serviceMap = new ConcurrentHashMap<>();
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if(bean instanceof ICouponHandlerService){
            // 获取bean的运行时对象类
            Class<?> clazz = bean.getClass();
            // 获取自定义的注解
            CouponHandlerProcessor annotation = clazz.getAnnotation(CouponHandlerProcessor.class);
            // TODO 可以在这里对ben进行校验
            if(annotation != null){
                // 绑定类型和处理器的关系
                serviceMap.put(annotation.value(), (ICouponHandlerService) bean);
                log.info("CouponHandlerFactory postProcessBeforeInitialization beanName:{},type:{}",beanName,annotation.value());
            }
        }
        return bean;
    }

    /**
     * 根据类型获取对应的处理器
     * @param type
     * @return
     */
    public ICouponHandlerService getHandler(CouponTypeEnum type){
        return serviceMap.get(type);
    }
}
